//
//  SharedContentView.swift
//  AppleAppDemo
//
//  Created by 刘忠华 on 2025/9/9.
//

import SwiftUI

/// 共享的主视图内容
struct SharedContentView: View {
    @State private var selectedTab = 0
    
    var body: some View {
        Group {
            if PlatformDetector.isTV {
                // Apple TV 使用焦点导航
                TVContentView()
            } else if PlatformDetector.isMacOS {
                // macOS 使用侧边栏布局
                MacContentView()
            } else {
                // iOS/iPadOS 使用标签栏
                MobileContentView()
            }
        }
    }
}

/// 移动设备内容视图（iOS/iPadOS）
struct MobileContentView: View {
    @State private var selectedTab = 0
    
    var body: some View {
        TabView(selection: $selectedTab) {
            NavigationStack {
                HomeView()
            }
            .tabItem {
                Image(systemName: "house.fill")
                Text("首页")
            }
            .tag(0)
            
            NavigationStack {
                FeaturesView()
            }
            .tabItem {
                Image(systemName: "star.fill")
                Text("功能")
            }
            .tag(1)
            
            NavigationStack {
                SettingsView()
            }
            .tabItem {
                Image(systemName: "gear")
                Text("设置")
            }
            .tag(2)
        }
    }
}

/// macOS 内容视图
struct MacContentView: View {
    @State private var selectedSidebarItem: SidebarItem? = .home
    
    var body: some View {
        NavigationSplitView {
            List(SidebarItem.allCases, selection: $selectedSidebarItem) { item in
                Label(item.title, systemImage: item.icon)
                    .tag(item)
            }
            .navigationTitle("AppleAppDemo")
        } detail: {
            Group {
                switch selectedSidebarItem {
                case .home:
                    HomeView()
                case .features:
                    FeaturesView()
                case .settings:
                    SettingsView()
                case .none:
                    HomeView()
                }
            }
            .navigationTitle(selectedSidebarItem?.title ?? "首页")
        }
    }
}

/// Apple TV 内容视图
struct TVContentView: View {
    @State private var selectedItem = 0
    @FocusState private var focusedItem: Int?
    @StateObject private var focusManager = TVFocusManager()
    private let items = ["首页", "功能", "设置"]
    
    var body: some View {
        VStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 40)) {
            Text("AppleAppDemo")
                .font(.largeTitle)
                .fontWeight(.bold)
            
            HStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 60)) {
                ForEach(0..<items.count, id: \.self) { index in
                    Button(action: {
                        print("SharedContentView: 点击导航按钮，索引: \(index)")
                        selectedItem = index
                        // 点击导航按钮后，设置页面索引并将焦点转移到内容区域
                        focusManager.setCurrentPageIndex(index)
                        focusManager.requestContentFocus()
                    }) {
                        VStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 20)) {
                            Image(systemName: iconForIndex(index))
                                .font(.system(size: PlatformConfig.fontSize(for: .tvOS, base: 40)))
                            
                            Text(items[index])
                                .font(.title2)
                        }
                        .foregroundColor(selectedItem == index ? .white : .gray)
                        .scaleEffect(selectedItem == index ? 1.1 : 1.0)
                        .animation(.easeInOut(duration: 0.2), value: selectedItem)
                    }
                    .buttonStyle(PlainButtonStyle())
                    .focused($focusedItem, equals: index)
                    .onKeyPress(.upArrow) {
                        // 当在导航按钮上按上键时，保持焦点在导航
                        return .handled
                    }
                    .onKeyPress(.downArrow) {
                        // 当在导航按钮上按下键时，将焦点转移到内容区域
                        // 不立即设置focusedItem = nil，让焦点自然转移到内容区域
                        focusManager.requestContentFocus()
                        return .handled
                    }
                }
            }
            
            Spacer()
            
            // 显示选中的内容
            NavigationStack {
                Group {
                    switch selectedItem {
                    case 0:
                        HomeView()
                            .onAppear {
                                focusManager.setCurrentPageIndex(0)
                            }
                    case 1:
                        FeaturesView()
                            .onAppear {
                                focusManager.setCurrentPageIndex(1)
                            }
                    case 2:
                        SettingsView()
                            .onAppear {
                                focusManager.setCurrentPageIndex(2)
                            }
                    default:
                        HomeView()
                    }
                }
                .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
        }
        .padding(PlatformConfig.spacing(for: .tvOS, base: 40))
        .environmentObject(focusManager)
        .onAppear {
            // 只在初始加载时设置焦点，避免干扰页面切换
            if focusedItem == nil {
                focusedItem = selectedItem
            }
        }
        .onChange(of: selectedItem) { newValue in
            print("SharedContentView: selectedItem改变为: \(newValue)")
            // 当选择改变时，不自动设置焦点到导航按钮
            // 焦点转移由点击事件或滚动到顶部事件处理
        }
        .onChange(of: focusManager.shouldFocusNavigation) { shouldFocus in
            if shouldFocus {
                // 当需要转移焦点到导航时，设置焦点到目标导航按钮
                print("SharedContentView: 设置导航焦点，目标索引: \(focusManager.targetNavigationIndex)")
                focusedItem = focusManager.targetNavigationIndex
                focusManager.reset()
            }
        }
    }
    
    private func iconForIndex(_ index: Int) -> String {
        switch index {
        case 0: return "house.fill"
        case 1: return "star.fill"
        case 2: return "gear"
        default: return "house.fill"
        }
    }
}

/// 侧边栏项目
enum SidebarItem: String, CaseIterable, Identifiable {
    case home = "home"
    case features = "features"
    case settings = "settings"
    
    var id: String { rawValue }
    
    var title: String {
        switch self {
        case .home: return "首页"
        case .features: return "功能"
        case .settings: return "设置"
        }
    }
    
    var icon: String {
        switch self {
        case .home: return "house.fill"
        case .features: return "star.fill"
        case .settings: return "gear"
        }
    }
}

#Preview {
    SharedContentView()
}
